package cn.acewill.yxd.yunxundian.adapter;

import android.app.Activity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.ui.MainActivity;

/**
 * Created by XXX on 2017/6/14.
 */

public class ScheduleRecycleAdapter extends RecyclerView.Adapter<ScheduleRecycleAdapter.MyViewHolder>{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private List<Schedule> mylist;
    private Activity activity;
    public MyCallBackClickListener mylistener;

    public ScheduleRecycleAdapter( List<Schedule> mylist,Activity activity,MyCallBackClickListener mylistener){
        this.mylist=mylist;
        this.activity=activity;
        this.mylistener=mylistener;
    }
    public ScheduleRecycleAdapter(List<Schedule> mylist,Activity activity){
        this.mylist=mylist;
        this.activity=activity;
    }
    public interface MyCallBackClickListener{
        void onEditorClick(Schedule schedule,int position);
        void onLookClick(Schedule schedule,int position);
        void onSignClick(Schedule schedule,int position);
        void onSubmitClick(Schedule schedule,int position);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(activity).inflate(R.layout.evaluation_info,parent,false);
        MyViewHolder holder=new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Schedule schedule=mylist.get(position);
        holder.binTag(schedule);

        settitle(schedule,holder);
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm");
        String thisdate=format.format(date);
        holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity,R.color.blue));
        setTimeAndStatus(schedule,holder,thisdate);
        setTime(schedule,holder);
      //  int sid=schedule.getStartUserId();
        int tid=schedule.getToUserId();
        if (MainActivity.id!=tid){
            //只查看
            setVisible(3,holder);
        }
        //if (schedule.getSubtitle()!=null&&schedule.getSubtitle().equals("职能")){
        //    setVisible(3,holder);
        //}

    }
    @Override
    public int getItemCount() {
        return mylist==null?0:mylist.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView storeName;
        TextView taskName;
        TextView taskStatus;
        TextView taskScore;
        TextView relStartTime;
        TextView endTime;
        TextView relHour;
        TextView endHour;
        TextView schStartTime;
        TextView schEndTime;
        TextView taskPublisher;
        TextView taskOperator;
        TextView taskEditor;
        TextView shopSign;
        TextView lookInfo;
        TextView submitData;
        LinearLayout timeLine;
        CardView frameCV;


        public MyViewHolder(View itemView) {
            super(itemView);
            timeLine = (LinearLayout) itemView.findViewById(R.id.timeLine);
            storeName = (TextView) itemView.findViewById(R.id.storeName);
            taskName = (TextView) itemView.findViewById(R.id.taskName);
            taskStatus = (TextView) itemView.findViewById(R.id.taskStatus);
            taskScore = (TextView) itemView.findViewById(R.id.taskScore);
            relStartTime = (TextView) itemView.findViewById(R.id.relStartTime);
            endTime = (TextView) itemView.findViewById(R.id.endTime);
            relHour = (TextView) itemView.findViewById(R.id.relHour);
            endHour = (TextView) itemView.findViewById(R.id.endHour);
            schStartTime = (TextView) itemView.findViewById(R.id.schStartTime);
            schEndTime = (TextView) itemView.findViewById(R.id.schEndTime);
            taskPublisher = (TextView) itemView.findViewById(R.id.taskPublisher);
            taskOperator = (TextView) itemView.findViewById(R.id.taskOperator);
            taskEditor = (TextView) itemView.findViewById(R.id.taskEditor);
            shopSign = (TextView) itemView.findViewById(R.id.shopSign);
            lookInfo = (TextView) itemView.findViewById(R.id.lookInfo);
            submitData = (TextView) itemView.findViewById(R.id.submitData);
            frameCV = (CardView) itemView.findViewById(R.id.evaCardHold);
            taskEditor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mylistener.onEditorClick((Schedule) taskEditor.getTag(),getLayoutPosition());
                }
            });
            lookInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mylistener.onLookClick((Schedule) lookInfo.getTag(),getLayoutPosition());
                }
            });
            shopSign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mylistener.onSignClick((Schedule) shopSign.getTag(),getLayoutPosition());
                }
            });
            submitData.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mylistener.onSubmitClick((Schedule) submitData.getTag(),getLayoutPosition());
                }
            });

        }

        public void binTag(Schedule schedule) {
            taskEditor.setTag(schedule);
            lookInfo.setTag(schedule);
            shopSign.setTag(schedule);
            submitData.setTag(schedule);
        }

//        @Override
//        public void onClick(View v) {
//
//            switch (v.getId()){
//                case R.id.taskEditor:
//
//
//                    break;
//                case R.id.lookInfo:
//
//                    break;
//                case R.id.shopSign:
//
//                    break;
//                case R.id.submitData:
//
//                    break;
//            }
//        }
    }


    /**
     * 设置title的值
     * @param schedule
     * @param holder
     */
    public void settitle(Schedule schedule,MyViewHolder holder){
        if (schedule.getTitle()==null){
            holder.taskName.setText("命名中....");
        }else{
            holder.taskName.setText(schedule.getTitle());
        }
        if(schedule.getShopID()==0){
            holder.storeName.setText("非门店任务");
        }else{
            Shop shop= null;
            try {
                shop = db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
            } catch (DbException e) {
                e.printStackTrace();
            }
            if(shop==null){
                holder.storeName.setText("");
            }else{
                holder.storeName.setText(shop.getShopName());
            }
        }

        if(schedule.getSubtitle()!=null&&schedule.getSubtitle().contains(","))
        {
            String[] tempStr = schedule.getSubtitle().split(",");
               // holder.taskOperator.setText(tempStr[2]);
            if (tempStr.length>=2){
                holder.taskScore.setText(tempStr[1]+"/"+tempStr[0]);
            }
        }

        try {
            //执行人
            Employee user=db.selector(Employee.class).where("ID","=",schedule.getToUserId()).findFirst();
            //发起人
            Employee startuser = db.selector(Employee.class).where("ID","=",schedule.getStartUserId()).findFirst();
            if (user!=null&&user.getFirstName()!=null)
               holder.taskOperator.setText("执行人："+user.getFirstName());
            else
                holder.taskOperator.setText("执行人：");
            if (startuser!=null&&startuser.getFirstName()!=null)
                  holder.taskPublisher.setText("发起人："+startuser.getFirstName());
            else
                holder.taskPublisher.setText("发起人：");

        } catch (DbException e) {
            e.printStackTrace();
        }


    }

    /**
     * 控制显影与颜色
     * @param schedule
     * @param holder
     */
    public void setTimeAndStatus(Schedule schedule, MyViewHolder holder, String data) {
        String schtime=schedule.getSchStartTime();
        if(schtime!="")
            schtime=schtime.replace("T"," ");
        int result = compare_date(schtime, data);
        int status = schedule.getStates();
        //不需要去做处理
//        if (schedule.getIsHidden() == 1) {
//            holder.taskName.setTextColor(ContextCompat.getColor(activity, R.color.titleColor));
//        }
        if (schedule.getIsAssign() == 1) {
            holder.frameCV.setBackgroundColor(ContextCompat.getColor(activity, R.color.omYellow));
        }
        if(schedule.getStartUserId()!=schedule.getToUserId())
        {
            holder.frameCV.setBackgroundColor(ContextCompat.getColor(activity, R.color.omYellow));
        }

        if (status == 1) {
            setVisible(status, holder);
            if (result == 1) {
                holder.taskStatus.setText("任务未开始");
                setColor(R.color.titleColor, holder);
            } else if (result == -1) {
                holder.taskStatus.setText("任务未开始(延误)");
                setColor(R.color.color_red, holder);
                holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity, R.color.color_red));
            } else {
                holder.taskStatus.setText("任务未开始");
                setColor(R.color.titleColor, holder);
            }
        }
        if (status == 2) {
            holder.taskStatus.setText("进行中");
            setVisible(status, holder);
            setColor(R.color.titleColor, holder);
        }

        if (status == 3) {
            if ( schedule.getIsNeedShopReport() == 1||schedule.getIsNeedShopReport() == 2){
                holder.taskStatus.setText("已提交");
                setColor(R.color.completeEva, holder);
                setVisible(status, holder);
                holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity, R.color.completeEva));
            }else{
                holder.taskStatus.setText("已提交");
                setVisible(status, holder);
                holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity, R.color.allComplete));
            }
        }
        if (status == 4) {
            if (schedule.getIsNeedShopReport() == 0 ||schedule.getIsNeedShopReport() == 3){
                holder.taskStatus.setText("已完成");
                setVisible(status, holder);
                setColor(R.color.allComplete, holder);
                holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity, R.color.allComplete));
            }else{
                holder.taskStatus.setText("已完成");
                setVisible(status, holder);
                holder.timeLine.setBackgroundColor(ContextCompat.getColor(activity, R.color.allComplete));
            }
        }
    }




    //显示查看
    public void setVisible(int status,MyViewHolder holder){
        if (status==1||status==2){
            holder.taskEditor.setVisibility(View.VISIBLE);
            holder.shopSign.setVisibility(View.VISIBLE);
            holder.lookInfo.setVisibility(View.GONE);
            holder.submitData.setVisibility(View.VISIBLE);
        }else{
            holder.lookInfo.setVisibility(View.VISIBLE);
            holder.taskEditor.setVisibility(View.GONE);
            holder.shopSign.setVisibility(View.GONE);
            holder.submitData.setText("发送");
            holder.submitData.setVisibility(View.VISIBLE);
        }
    }

    public void setColor(int color,MyViewHolder holder){
        holder.storeName.setTextColor(ContextCompat.getColor(activity, color));
        holder.taskStatus.setTextColor(ContextCompat.getColor(activity, color));
        holder.taskName.setTextColor(ContextCompat.getColor(activity, color));
        holder.taskScore.setTextColor(ContextCompat.getColor(activity, color));
    }

    /*时间的比较*/
    public static int compare_date(String DATE1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 1.先判断是否存在日程的时间
     *2.判断日程时间的大小，在设置显示页面的具体值
     * @param schedule
     */
    public void setTime(Schedule schedule,MyViewHolder holder){
        String[] restartime=null;
        String[] startime=null;
        String[] endtime=null;
        String[] reendtime=null;
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String[] thisdate=format.format(date).split("-");
        if (schedule.getRealStartTime()==null){
            holder.relStartTime.setText("******");
            holder.relHour.setText("***");
        }else{
            restartime=schedule.getRealStartTime().split("\\-|T");
            holder.relStartTime.setText("开始:"+restartime[0]+"年"+restartime[1]+"月"+restartime[2]+"日");
            holder.relHour.setText("开始时间:"+restartime[3].substring(0,5));
        }
        if (schedule.getSchStartTime()==null){
            holder.schStartTime.setText("*****");
        }else{
            startime=schedule.getSchStartTime().split("\\-|T");
            if (restartime!=null){
                if (startime[0]==restartime[0]&&startime[1]==restartime[1]&&startime[2]==restartime[2]){
                    holder.schStartTime.setText("计划:"+startime[3].substring(0,5));
                }else{
                    holder.schStartTime.setText("计划:"+startime[0]+"年"+startime[1]+"月"+startime[2]+"日");
                }
            }else{
                holder.schStartTime.setText("计划:"+startime[0]+"年"+startime[1]+"月"+startime[2]+"日");
            }

        }
        if (schedule.getRealEndTime()==null){
            holder.endTime.setText("******");
            holder.endHour.setText("***");
        }else {
            if (schedule.getRealEndTime().contains("T")) {
                reendtime = schedule.getRealEndTime().split("\\-|T");
                holder.endTime.setText("完成:" + reendtime[1] + "月" + reendtime[2] + "日");
                holder.endHour.setText(reendtime[3].substring(0, 5));
            }
            else if (schedule.getRealEndTime().contains(" ")) {
                reendtime = schedule.getRealEndTime().split("\\-| ");
                holder.endTime.setText("完成" + reendtime[1] + "月" + reendtime[2] + "日");
                holder.endHour.setText(reendtime[3].substring(0, 5));
            }
        }
        if (schedule.getSchEndTime()==null){
            holder.schEndTime.setText("****");
        }else{
            endtime=schedule.getSchEndTime().split("\\-|T");
            holder.schEndTime.setText("计划完成:"+endtime[3].substring(0,5));
        }
    }
}
